package com.code.aspect;

import com.code.commons.constants.ServerConstants;
import com.code.commons.enums.ResultCode;
import com.code.commons.exceptions.BusinessException;
import com.code.commons.web.annotations.SystemProtect;
import com.code.user.client.UserClient;
import com.code.user.model.bo.SystemSettingBO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 系统更新切面
 *
 * @author tangyifei
 * @since 2020年2月7日11:54:40
 **/
@Aspect
@Configuration
@Slf4j
public class SystemProtectAspect {

    @Resource
    UserClient userClient;

    @Around("execution(* com.code.web ..*(..) )")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
//        Class<?> targetClass = method.getDeclaringClass();
        SystemProtect systemProtect = method.getAnnotation(SystemProtect.class);
        if (null != systemProtect) {
            SystemSettingBO systemSettingBO = userClient.getSystemSettingBySystemKey(ServerConstants.SYSTEM_PROTECT);
            if (null != systemSettingBO) {
                String systemProtectSwitch = systemSettingBO.getSystemValue();
                if ("1".equals(systemProtectSwitch)) {
                    throw new BusinessException(ResultCode.SYSTEM_PROTECT);
                }
            }
        }
        return joinPoint.proceed();
    }

}
